package com.penghk.springbootdemo.controller;

import com.penghk.springbootdemo.entity.People;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

public class MyMessageConverter extends AbstractHttpMessageConverter<People> {

    public MyMessageConverter() {
        super(new MediaType("application","x-wisely" , Charset.forName("utf-8")));
    }

    @Override
    protected boolean supports(Class<?> aClass) {
        return true;
//        return false;
    }

    @Override
    protected People readInternal(Class<? extends People> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

        String temp  = StreamUtils.copyToString(inputMessage.getBody() , Charset.forName("utf-8"));
        String[] attrs = temp.split("-");
        return new People(Long.parseLong(attrs[0]) , attrs[1] , Integer.parseInt(attrs[2]));
    }

    @Override
    protected void writeInternal(People people, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        String out = "hello : "+people.getName();
        outputMessage.getBody().write(out.getBytes());
    }


}
